use rustcloud_core::{
    RustCloudApplicationBuilder, RegistryConfig, RegistryType, ApplicationConfig,
    LoadBalancerStrategy, TransportConfig, CircuitBreakerConfig
};
use rustcloud_registry::NacosRegistry;
use rustcloud_loadbalancer::LoadBalancerManager;
use rustcloud_transport::HttpTransport;
use rustcloud_circuit_breaker::DefaultCircuitBreaker;
use rustcloud_macros::remote_service;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use axum::{extract::State, routing::post, Router, Json};
use tracing::{info, Level};
use tracing_subscriber::FmtSubscriber;

// 用户数据结构 (从用户服务)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    pub id: u64,
    pub name: String,
    pub email: String,
    pub age: u32,
}

#[derive(Debug, Deserialize)]
pub struct CreateUserRequest {
    pub name: String,
    pub email: String,
    pub age: u32,
}

// 定义用户服务客户端接口
#[remote_service(\"user-service\")]
pub trait UserService {
    async fn get_user(&self, user_id: u64) -> Result<Option<User>, String>;
    async fn create_user(&self, request: CreateUserRequest) -> Result<User, String>;
    async fn list_users(&self) -> Result<Vec<User>, String>;
}

// 订单数据结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Order {
    pub id: u64,
    pub user_id: u64,
    pub user_name: String, // 从用户服务获取
    pub product_name: String,
    pub quantity: u32,
    pub price: f64,
    pub total: f64,
    pub created_at: String,
}

#[derive(Debug, Deserialize)]
pub struct CreateOrderRequest {
    pub user_id: u64,
    pub product_name: String,
    pub quantity: u32,
    pub price: f64,
}

// 定义订单服务接口
#[remote_service(\"order-service\")]
pub trait OrderService {
    async fn get_order(&self, order_id: u64) -> Result<Option<Order>, String>;
    async fn create_order(&self, request: CreateOrderRequest) -> Result<Order, String>;
    async fn list_orders(&self) -> Result<Vec<Order>, String>;
    async fn get_user_orders(&self, user_id: u64) -> Result<Vec<Order>, String>;
}

// 实现订单服务
#[derive(Clone)]
pub struct OrderServiceImpl {
    // 简化实现，使用内存存储
    orders: Arc<std::sync::RwLock<std::collections::HashMap<u64, Order>>>,
    next_id: Arc<std::sync::atomic::AtomicU64>,
    // 用户服务客户端
    user_client: UserServiceClient,
}

impl OrderServiceImpl {
    pub fn new(user_client: UserServiceClient) -> Self {
        let orders = Arc::new(std::sync::RwLock::new(std::collections::HashMap::new()));
        let next_id = Arc::new(std::sync::atomic::AtomicU64::new(1));
        
        Self { orders, next_id, user_client }
    }
}

#[async_trait::async_trait]
impl OrderService for OrderServiceImpl {
    async fn get_order(&self, order_id: u64) -> Result<Option<Order>, String> {
        let orders = self.orders.read().map_err(|e| e.to_string())?;
        Ok(orders.get(&order_id).cloned())
    }

    async fn create_order(&self, request: CreateOrderRequest) -> Result<Order, String> {
        // 首先从用户服务获取用户信息
        let user = match self.user_client.get_user(request.user_id).await {
            Ok(Some(user)) => user,
            Ok(None) => return Err(format!(\"用户 {} 不存在\", request.user_id)),
            Err(e) => return Err(format!(\"获取用户信息失败: {}\", e)),
        };

        let mut orders = self.orders.write().map_err(|e| e.to_string())?;
        let id = self.next_id.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        
        let total = request.price * request.quantity as f64;
        let order = Order {
            id,
            user_id: request.user_id,
            user_name: user.name,
            product_name: request.product_name,
            quantity: request.quantity,
            price: request.price,
            total,
            created_at: chrono::Utc::now().format(\"%Y-%m-%d %H:%M:%S\").to_string(),
        };
        
        orders.insert(id, order.clone());
        info!(\"创建订单: {:?}\", order);
        Ok(order)
    }

    async fn list_orders(&self) -> Result<Vec<Order>, String> {
        let orders = self.orders.read().map_err(|e| e.to_string())?;
        Ok(orders.values().cloned().collect())
    }

    async fn get_user_orders(&self, user_id: u64) -> Result<Vec<Order>, String> {
        let orders = self.orders.read().map_err(|e| e.to_string())?;
        Ok(orders.values()
            .filter(|order| order.user_id == user_id)
            .cloned()
            .collect())
    }
}

// HTTP路由处理器
async fn health_check() -> &'static str {
    \"OK\"
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化日志
    let subscriber = FmtSubscriber::builder()
        .with_max_level(Level::INFO)
        .finish();
    tracing::subscriber::set_global_default(subscriber)
        .expect(\"设置默认订阅者失败\");

    info!(\"启动订单服务...\");

    // 读取配置
    let app_config = ApplicationConfig {
        name: \"order-service\".to_string(),
        version: \"1.0.0\".to_string(),
        port: 8082,
        host: Some(\"127.0.0.1\".to_string()),
        group: Some(\"DEFAULT_GROUP\".to_string()),
        namespace: Some(\"public\".to_string()),
        metadata: std::collections::HashMap::new(),
    };

    // 创建注册中心
    let registry_config = RegistryConfig {
        registry_type: RegistryType::Nacos,
        server_addr: \"127.0.0.1:8848\".to_string(),
        namespace: Some(\"public\".to_string()),
        group: Some(\"DEFAULT_GROUP\".to_string()),
        username: None,
        password: None,
    };
    
    let registry = Arc::new(NacosRegistry::new(registry_config)?);

    // 创建负载均衡器
    let load_balancer = Arc::new(LoadBalancerManager::new(LoadBalancerStrategy::RoundRobin));
    
    // 创建传输层
    let transport = Arc::new(HttpTransport::with_config(TransportConfig::default()));
    
    // 创建熔断器
    let circuit_breaker = Arc::new(DefaultCircuitBreaker::new(CircuitBreakerConfig::default()));

    // 创建用户服务客户端
    let user_client = UserServiceClient::new(
        load_balancer.clone(),
        transport.clone(),
        registry.clone(),
    );

    // 创建订单服务实现
    let order_service = Arc::new(OrderServiceImpl::new(user_client));

    // 创建HTTP路由
    let app = Router::new()
        .route(\"/health\", axum::routing::get(health_check))
        .route(\"/api/order-service/get_order\", post({
            let service = order_service.clone();
            move |Json(params): Json<serde_json::Value>| async move {
                let order_id: u64 = params.get(\"order_id\")
                    .and_then(|v| v.as_u64())
                    .ok_or_else(|| \"Missing order_id parameter\")?;
                
                match service.get_order(order_id).await {
                    Ok(order) => Ok(Json(serde_json::json!({ \"success\": true, \"data\": order }))),
                    Err(e) => Ok(Json(serde_json::json!({ \"success\": false, \"error\": e }))),
                }
            }
        }))
        .route(\"/api/order-service/create_order\", post({
            let service = order_service.clone();
            move |Json(request): Json<CreateOrderRequest>| async move {
                match service.create_order(request).await {
                    Ok(order) => Ok(Json(serde_json::json!({ \"success\": true, \"data\": order }))),
                    Err(e) => Ok(Json(serde_json::json!({ \"success\": false, \"error\": e }))),
                }
            }
        }))
        .route(\"/api/order-service/list_orders\", post({
            let service = order_service.clone();
            move |Json(_): Json<serde_json::Value>| async move {
                match service.list_orders().await {
                    Ok(orders) => Ok(Json(serde_json::json!({ \"success\": true, \"data\": orders }))),
                    Err(e) => Ok(Json(serde_json::json!({ \"success\": false, \"error\": e }))),
                }
            }
        }))
        .route(\"/api/order-service/get_user_orders\", post({
            let service = order_service.clone();
            move |Json(params): Json<serde_json::Value>| async move {
                let user_id: u64 = params.get(\"user_id\")
                    .and_then(|v| v.as_u64())
                    .ok_or_else(|| \"Missing user_id parameter\")?;
                
                match service.get_user_orders(user_id).await {
                    Ok(orders) => Ok(Json(serde_json::json!({ \"success\": true, \"data\": orders }))),
                    Err(e) => Ok(Json(serde_json::json!({ \"success\": false, \"error\": e }))),
                }
            }
        }));

    // 创建并启动RustCloud应用
    let app_handle = {
        let registry_clone = registry.clone();
        tokio::spawn(async move {
            let rustcloud_app = RustCloudApplicationBuilder::from_config(app_config)
                .registry(registry_clone)
                .build();
            
            if let Err(e) = rustcloud_app.run().await {
                eprintln!(\"RustCloud应用启动失败: {}\", e);
            }
        })
    };

    // 启动HTTP服务器
    let listener = tokio::net::TcpListener::bind(\"127.0.0.1:8082\").await?;
    info!(\"订单服务在 http://127.0.0.1:8082 启动\");
    
    axum::serve(listener, app).await?;
    
    // 等待应用句柄完成
    let _ = app_handle.await;
    
    Ok(())
}
